package com.ruoyi.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpRequest {

    private static final Logger logger = LoggerFactory.getLogger(HttpRequest.class);

    /**
     *处理Https GET|POST 请求
     * @param httpUrl 请求地址
     * @param requestMethod 请求方法（GET|POST）
     * @param outputStr
     * @date 2017年3月31日 上午10:35:32
     */
    public static String httpRequest(String httpUrl, String requestMethod,String outputStr) {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(httpUrl);
            URLConnection rulConnection = url.openConnection();
            HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection;
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            httpUrlConnection.setUseCaches(false);
            httpUrlConnection.setRequestProperty("Content-Type",
                    "application/json");
            httpUrlConnection
                    .setRequestProperty("POST", "/violations HTTP/1.1");
            httpUrlConnection.setRequestMethod(requestMethod);
            httpUrlConnection.connect();

            if (null != outputStr) {
                OutputStream outputStream = httpUrlConnection.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            InputStream inputStream = httpUrlConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            httpUrlConnection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

}
